package lion.mail;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.activation.DataSource;
import javax.activation.FileTypeMap;
import javax.mail.util.ByteArrayDataSource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

/**
 * 邮件的附件，该类由{@link MailBuilder}在构建有附件的邮件时使用
 *
 * @author lion
 * @date 2011-5-26
 */
public class Attachment {

	private String cid;
	private String name;
	// private InputStream inputStream;
	private static volatile int basicCid = 1;
	private DataSource dataSource;

	public static String generateCID() {

		return String.valueOf("lion_" + basicCid++);
	}

	public String getCid() {

		return cid;
	}

	public void setCid(String cid) {

		this.cid = cid;
	}

	public String getName() {

		return name;
	}

	public void setName(String name) {

		this.name = name;
	}

	public void attach(String file) {

		attach(new File(file));
	}

	public void attach(File file) {

		try {
			attach(FileUtils.readFileToByteArray(file));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void attach(InputStream stream) {

		try {
			attach(IOUtils.toByteArray(stream));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void attach(byte[] data) {

		this.dataSource = new ByteArrayDataSource(data, Attachment.getContextType(this.name));
	}

	public DataSource getDataSource() {

		return this.dataSource;
	}

	public static String getContextType(String name) {

		String contextType = "application/octet-stream";
		if (StringUtils.isNotBlank(name)) {
			contextType = FileTypeMap.getDefaultFileTypeMap().getContentType(name);
		}
		return contextType;
	}
}
